package forum;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;

import processing.core.PApplet;
import processing.core.PImage;
import processing.core.PVector;


public class PointToLine extends PApplet{

	PImage imgRaster;

	public void setup(){
		size(462, 424);
		imgRaster = loadImage("data/points2.png");
		println("Image size " + imgRaster.width + ", " + imgRaster.height);
		long time = millis();
		PVector[] border = rasterToVector(imgRaster);
		println("Time to vectorize = " + (millis() - time) + " milliseconds" );
		println("Number of points " + border.length);
		// Draw border and save image
		background(0,32,0);
		stroke(0,255,0);
		strokeWeight(1);
		
		if(border.length > 1){
			for(int i = 1; i < border.length; i++)
				line(border[i-1].x, border[i-1].y, border[i].x, border[i].y);
		}
		redraw();
	}

	public PVector[] rasterToVector(PImage img){
		int w = img.width;
		int h = img.height;

		ArrayList<PVector> v = new ArrayList<PVector>();
		img.loadPixels();
		// Stage 1 create vectors for each boundary pixel
		int r, g, b, c;
		int index = 0;
		for(int k = 0; k < h; k++){
			for(int j = 0; j < w; j++){
				c = img.pixels[index];
				r = ((c & 0xff0000) >> 16);
				g = ((c & 0xff00) >> 8);
				b = (c & 0xff);
				if(r < 128 || g < 128 || b < 128) {
					img.pixels[index] = 0xffff0000;
					v.add(new PVector(j, k));
				}
				index++;
			}
		}
		img.updatePixels();
		// Get an array of EVectors for speed
		PVector[] vecs = v.toArray(new PVector[v.size()]);
		int nbrVecs = vecs.length;
		if(vecs.length > 2){
			for(int i = 1; i < nbrVecs - 2; i++) {
				PVector pivot = vecs[i-1];
				DistanceComparitor comp = new DistanceComparitor(pivot.x,  pivot.y);
				Arrays.sort(vecs, i, nbrVecs - 1, comp);
			}
		}
		// Convert to PVector
		return vecs;
	}

	public class DistanceComparitor implements Comparator<PVector> {
		private final float x;
		private final float y;

		public DistanceComparitor(float x, float y){
			this.x = x;
			this.y = y;
		}

		@Override
		public int compare(PVector v1, PVector v2) {
			float v1d2 = (v1.x - x)*(v1.x - x) + (v1.y - y)*(v1.y - y);
			float v2d2 = (v2.x - x)*(v2.x - x) + (v2.y - y)*(v2.y - y);
			if(v1d2 == v2d2)
				return 0;
			else
				return (v1d2 < v2d2) ? -1 : 1;
		}

	}

}



